package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Contract;
import com.tianxin.workbao.workBao.bean.ContractDao;
import com.tianxin.workbao.workBao.bean.ContractStatistic;
import com.tianxin.workbao.workBao.bean.ContractStatisticDao;
import com.tianxin.workbao.workBao.bean.CtCoaltype;
import com.tianxin.workbao.workBao.bean.CtCoaltypeDao;
import com.tianxin.workbao.workBao.bean.PreSettlement;
import com.tianxin.workbao.workBao.bean.PreSettlementDao;
import com.tianxin.workbao.workBao.bean.VContract;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/26.
 */

public class ContractProvide extends BaseDataProvide {
    private Integer mPage;
    private List<VContract> vContractList;
    private VContract mContract;
    private UpdateListViewListener mUpdateListViewListener;
    private ContractDao contractDao;
    private CtCoaltypeDao contractCoalDao;
    private PreSettlementDao preSettlementDao;
    private int contractType;
    private ContractStatistic statistic;
    private boolean isGetData = true;
    private boolean isStatistic = false;

    public ContractProvide(Context context, UpdateListViewListener listener) {
        super(context);
        mUpdateListViewListener = listener;
        contractDao = GreenDaoHelper.newInstance().getDaoSession().getContractDao();
        contractCoalDao = GreenDaoHelper.newInstance().getDaoSession().getCtCoaltypeDao();
        preSettlementDao = GreenDaoHelper.newInstance().getDaoSession().getPreSettlementDao();
    }

    private void getFromDb() {
        Query<Contract> query = contractDao.queryBuilder()
                .where(ContractDao.Properties.Isis.eq(1))
                .where(ContractDao.Properties.Cttype.eq(contractType))
                .offset((mPage - 1) * Constant.COAL_PAGE_SIZE)
                .limit(Constant.COAL_PAGE_SIZE)
                .build();
        List<Contract> contracts = query.list();
        if (vContractList == null) {
            vContractList = new ArrayList<>();
        }
        VContract vContract;
        for (int i = 0; i < contracts.size(); i++) {
            vContract = new VContract();
            vContract.setContract(contracts.get(i));
            Query<CtCoaltype> coalQuery = contractCoalDao.queryBuilder()
                    .where(CtCoaltypeDao.Properties.Contractid.eq(contracts.get(i).getId()))
                    .build();
            List<CtCoaltype> coalList = coalQuery.list();
            vContract.setCoalTypeList(coalList);

            Query<PreSettlement> preSettlementQuery = preSettlementDao.queryBuilder()
                    .where(PreSettlementDao.Properties.Contractid.eq(contracts.get(i).getId()))
                    .limit(1)
                    .build();
            List<PreSettlement> preSettlementList = preSettlementQuery.list();
            vContract.setPreSettlement(preSettlementList.get(0));
            vContractList.add(vContract);
        }
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        if (vContractList != null && !vContractList.isEmpty()) {
                            vContractList.clear();
                        }
                        if (isGetData == false) {
                            mUpdateListViewListener.showMessage("ok");
                            return;
                        }
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                    vContractList = JSON.parseArray(dataJson, VContract.class);
                                    refreshUI();
                                    saveToDb(vContractList);
                                } else {
                                    if (isStatistic == false) {
                                        mContract = JSON.parseObject(dataJson, VContract.class);
                                        saveToDb(mContract);
                                    } else {
                                        statistic = JSON.parseObject(dataJson, ContractStatistic.class);
                                        saveToDb(statistic);
                                    }
                                    refreshUI();

                                }
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("类型转换出错" + e.getMessage());
                            }
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        if (isGetData == false) {
                            mUpdateListViewListener.showMessage("failure" + information);
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                        if (vContractList != null && !vContractList.isEmpty()) {
                            vContractList.clear();
                        }
                        refreshUI();
                    }
                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        if (isStatistic == true) {
            ContractStatisticDao contractStatisticDao = mGreenDaoHelper.getDaoSession().getContractStatisticDao();
            contractStatisticDao.insertOrReplace((ContractStatistic) obj);
            return;
        }
        if (obj instanceof List) {
            for (int i = 0; i < vContractList.size(); i++) {
                contractDao.insertOrReplace(vContractList.get(i).getContract());
                for (int j = 0; j < vContractList.get(i).getCoalTypeList().size(); j++) {
                    contractCoalDao.insertOrReplace(vContractList.get(i).getCoalTypeList().get(j));
                }
                if (vContractList.get(i).getPreSettlement() != null) {
                    preSettlementDao.insertOrReplace(vContractList.get(i).getPreSettlement());
                }
            }
        } else {
            VContract vContract = (VContract) obj;
            contractDao.insertOrReplace(vContract.getContract());
            for (int j = 0; j < vContract.getCoalTypeList().size(); j++) {
                contractCoalDao.insertOrReplace(vContract.getCoalTypeList().get(j));
            }
            if (vContract.getPreSettlement() != null) {
                preSettlementDao.insertOrReplace(vContract.getPreSettlement());
            }
        }

    }

    /**
     * get data
     *
     * @param page
     */
    public void getdatas(int type, int page) {
        mPage = page;
        this.contractType = type;
        isGetData = true;
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb();
            refreshUI();
        } else {
            getFromServer();
        }

    }


    /**
     * update the coal data  from server
     */
    private void getFromServer() {
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("page", mPage + "");
        map.put("type", contractType + "");
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(
                URL.getContractUrl(), params), getDisposeDataHandle());
    }

    @Override
    public void refreshUI() {
        if (isStatistic == true) {
            mUpdateListViewListener.onRefreshData(statistic);
            return;
        }
        if (mPage > 1) {
            mUpdateListViewListener.onLoadMoreData(vContractList);
        } else {
            mUpdateListViewListener.onRefreshData(vContractList);
        }
    }


    // oauth
    public void oauth(Contract contract) {
        isGetData = false;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("contract", JSON.toJSONString(contract));
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(
                    URL.getOauthContractUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage(
                    mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void statistic() {
        isGetData = true;
        isStatistic = true;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(
                    URL.getContractstatisUrl(), params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage(
                    mContext.getResources().getString(R.string.poor_network));
            statisticFromDb();
            refreshUI();
        }

    }

    private void statisticFromDb() {
        ContractStatisticDao contractStatisticDao = mGreenDaoHelper.getDaoSession().getContractStatisticDao();
        List<ContractStatistic> list = contractStatisticDao.queryBuilder().list();
        if (list != null) {
            statistic = list.get(0);
        }
    }
/**
 *
 */
}
